<?php

require_once 'config.php';

/****
 * PHP proxy for using the Bing Search API with AJAX
 */

$rootUri = 'https://api.datamarket.azure.com/Bing/Search';

$query = $_GET['q'];

// Get the service operation. Default to Web.

$serviceOp = 'Image';

// Get the market. Default to en-us.

$market = ($_GET['market']) ? $_GET['market'] : 'es-XL';

// Encode the query along with the single quotation marks that must surround it.

$query = urlencode("'$query'");

// Encode the market along with the single quotation marks that must surround it.

$market = urlencode("'$market'");

// Construct the full URL for the query.

$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query&Market=$market";

// Encode the credentials and create the stream context.

$context = stream_context_create(
  array('http' => array('request_fulluri' => true,
                       'ignore_errors' => true,
                       'header' => 'Authorization: Basic ' .
                         base64_encode("$g_bing_account_key:$g_bing_account_key"))));

// Get the response from Bing.

$response = file_get_contents($requestUri, 0, $context);

// Send the response back to the browser.

echo $response;
?>